package net.lovesrc.allin.jobs.backup;

import com.alibaba.fastjson.JSONObject;
import net.lovesrc.allin.biz.stl.StlService;
import net.lovesrc.allin.biz.user.UserService;
import net.lovesrc.allin.jobs.base.BaseJob;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

//@Component
@Profile("live")
public class StlSyncSellJyStatusJob extends BaseJob {

    @Autowired
    private StlService stlService;

    @Override
    public void runOnce() throws IOException {
        boolean autoConfirmSellJy = tryGetProperties(boolean.class, false, "Stl_Auto_Confirm_Sell_Jy");
        stlService.syncSellJyStatus(!autoConfirmSellJy);
        // 自动确认卖出交易
        if (autoConfirmSellJy) {
            List<JSONObject> rows = queryForRows(jdbcTemplate, "select * from t_stl_sell where status = 'Waiting_Seller_Confirm' and hasTryOcrConfirm = 0 and payTime < ?",
                    DateUtils.addSeconds(new Date(), -RandomUtils.nextInt(10, 20))
            );
            for (JSONObject row : rows) {
                Integer jyId = row.getInteger("jyId");
                jdbcTemplate.update("update t_stl_sell set hasTryOcrConfirm = 1 where jyId = ?", jyId);
                if (stlService.canAutoConfirmSellJy(jyId)) {
                    stlService.confirmSellJY(UserService.SYSTEM, jyId);
                    jdbcTemplate.update("update t_stl_sell set byOcrConfirm = 1 where jyId = ?", jyId);
                } else {
                    String text = String.format("！！！, Alipay: %s, 无法系统自动确认", row.getString("alipayRealName"));
                    notificationService.syncEmail(text);
                }
            }
        }
    }

    @Override
    protected long intervalMilliseconds() {
        return TimeUnit.SECONDS.toMillis(5);
    }

}
